package com.ksy.common.dialog;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.ksy.common.R;
import com.ksy.common.utils.BaseAdapter;
import com.ksy.common.utils.BaseHolder;
import com.ksy.common.view.HLineDivider;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ItemsDialog<T> extends BottomDialog {
    private ItemChooseListener chooseListener;
    private List<T> allItems = new ArrayList<>();
    private RecyclerView recycler;

    public ItemsDialog(@NonNull Context context) {
        super(context);
    }

    public ItemsDialog(@NonNull Context context, T[] items, ItemChooseListener chooseListener) {
        super(context);
        this.chooseListener = chooseListener;
        List<T> list = null;
        if (items != null) {
            list = Arrays.asList(items);
        }
        if (list != null) {
            allItems.addAll(list);
        }
    }

    public ItemsDialog(@NonNull Context context, List<T> items, ItemChooseListener chooseListener) {
        super(context);
        this.chooseListener = chooseListener;
        if (items != null) {
            allItems.addAll(items);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.common_layout_dialog_items);
        findViewById(R.id.dialog_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        recycler = findViewById(R.id.recycler);
        recycler.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
        recycler.addItemDecoration(new HLineDivider());
        initAdapter();
    }

    private void initAdapter() {
        BaseAdapter<T, BaseHolder> adapter = new BaseAdapter<T, BaseHolder>(R.layout.common_item_text, allItems) {
            @Override
            protected void convert(BaseHolder helper, int position) {
                TextView text = helper.getView(R.id.tv);
                text.setText(allItems.get(position).toString());
            }
        };
        adapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (chooseListener != null) {
                    chooseListener.choose(ItemsDialog.this, position);
                }
            }
        });
        recycler.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }


    public interface ItemChooseListener {
        void choose(ItemsDialog dialog, int position);
    }
}
